<template>
    <el-dialog
        :title="title"
        :visible.sync="isShow"
        width="50%"
        :before-close="close"
        center
        class="person-group"
        :close-on-click-modal="false"
    >
        <div class="box">
            <p v-if="tips" class="tips">{{ tips }}</p>
            <el-tabs v-model="activeName" @tab-click="handleTabclick">
                <el-tab-pane
                    v-for="(item, index) in tabs"
                    :key="index"
                    :label="item.label"
                    :name="item.name"
                >
                </el-tab-pane>
            </el-tabs>
            <div class="content-box" v-if="activeName === 'town'">
                <div class="content-handle">
                    <el-input
                        class="filter-input"
                        placeholder="搜索内容"
                        size="mini"
                        prefix-icon="el-icon-search"
                        v-model="filterValue"
                    ></el-input>
                    <el-checkbox
                        v-if="!filterValue"
                        :indeterminate="isIndeterminate"
                        v-model="checkAll"
                        @change="handleCheckAllChange"
                        >全选</el-checkbox
                    >
                </div>
                <el-tree
                    class="filter-tree"
                    :data="filterOptionsList"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    show-checkbox
                    node-key="id"
                    default-expand-all
                    :filter-node-method="filterNode"
                    ref="town"
                    @check="handlecheck"
                >
                </el-tree>
            </div>
            <div class="content-box" v-if="activeName === 'village'">
                <div class="content-handle">
                    <el-input
                        class="filter-input"
                        placeholder="搜索内容"
                        size="mini"
                        prefix-icon="el-icon-search"
                        v-model="filterText"
                    ></el-input>
                    <el-checkbox
                        v-if="!filterText"
                        :indeterminate="isIndeterminate1"
                        v-model="checkAll1"
                        @change="handleCheckAllChangevillage"
                        >全选</el-checkbox
                    >
                </div>
                <el-tree
                    class="filter-tree"
                    :data="newVillageData"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    show-checkbox
                    node-key="id"
                    default-expand-all
                    :filter-node-method="filterNode"
                    ref="village"
                    @check="handlecheck"
                >
                </el-tree>
            </div>
            <div class="selected-box">
                <p class="box-title">已选</p>
                <div class="badge-delete-box">
                    <div
                        v-for="(item, index) in itemList"
                        :key="index"
                        class="badge-delete"
                    >
                        <p>{{ item.name }}</p>
                        <i
                            v-if="!item.disabled"
                            class="el-icon-error"
                            @click="deleteItem(index)"
                        ></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="confirm">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";

@Component({
    components: {}
})
export default class Dialog extends Vue {
    @Prop({ type: String, default: "人员选择" })
    title!: string;

    @Prop({ type: String, default: "" })
    tips!: string;

    @Prop({
        type: Object,
        required: true,
        default: () => {
            return {};
        }
    })
    authArea!: any;

    @Prop({
        type: Object,
        required: true,
        default: () => {
            return {};
        }
    })
    user!: any;

    @Prop({
        type: Array,
        required: true,
        default: () => {
            return [];
        }
    })
    tabs!: any[];

    @Prop({
        type: Array,
        required: true,
        default: () => {
            return [];
        }
    })
    selectedList!: any[];

    @Prop({
        type: Array,
        default: () => {
            return [];
        }
    })
    disabledList!: any[];

    isShow = false;
    activeName = "";
    filterValue = "";
    filterText = "";
    optionsList: any[] = [];
    itemList: any[] = [];
    defaultProps = {
        children: "children",
        label: "name"
    };

    townitemList: any[]=[];
    villageitemList: any[]=[];

    isIndeterminate = false;
    checkAll = false;
    isIndeterminate1 = false;
    checkAll1 = false;
    villageData: any[] = [];
    townData: any[] = [];

    @Watch("filterValue")
    change(val: any) {
        (this.$refs.town as any).filter(val);
    }

    @Watch("filterText")
    changeText(val: any) {
        (this.$refs.village as any).filter(val);
    }

    @Watch("activeName")
    changeShow(val: any) {
        if (val) {
            this.handeleSetChecked(val);
            if (this.disabledList.length) {
                this.$nextTick(() => {
                    (this.$refs[val] as any).setCheckedKeys(this.disabledList);
                });
            }
        }
    }

    @Watch("filterOptionsList")
    changeShowVal(val: any) {
        if (val && this.selectedList.length) {
            val.forEach((item: any) => {
                item.children.forEach((sub: any) => {
                    this.selectedList.forEach((it: any) => {
                        if (it === sub.id) {
                            this.townitemList.push(sub);
                        }
                    });
                });
            });
            this.itemList = [
                ...this.townitemList,
                ...this.villageitemList
            ];
            this.judgmentState();
            if (this.activeName === "town") {
                this.handeleSetChecked("town");
            } else {
                this.handeleSetChecked("village");
            }
        }
    }

    @Watch("newVillageData")
    changeTsVal(val: any) {
        if (val && this.selectedList.length) {
            val.forEach((item: any) => {
                item.children.forEach((sub: any) => {
                    this.selectedList.forEach((it: any) => {
                        if (it === sub.id) {
                            this.villageitemList.push(sub);
                        }
                    });
                });
            });
            this.itemList = [
                ...this.townitemList,
                ...this.villageitemList
            ];
            this.judgmentState();
            if (this.activeName === "town") {
                this.handeleSetChecked("town");
            } else {
                this.handeleSetChecked("village");
            }
        }
    }

    get filterOptionsList() {
        const ArrayList = JSON.parse(JSON.stringify(this.townData));
        if (ArrayList.length) {
            const arr: any[] = [];
            let obj: any = {};
            ArrayList.forEach((item: any) => {
                obj = {
                    children: item,
                    id: `zdy${item[0].id}`,
                    name: `${item[0].governmentName}`
                };
                arr.push(obj);
            });
            return arr;
        }
    }

    get newVillageData() {
        const ArrayList = JSON.parse(JSON.stringify(this.villageData));
        if (ArrayList.length) {
            const arr: any[] = [];
            let obj: any = {};
            ArrayList.forEach((item: any) => {
                obj = {
                    children: item,
                    id: `zdy${item[0].id}`,
                    name: `${item[0].governmentName}`
                };
                arr.push(obj);
            });
            return arr;
        }
    }

    mounted() {
        this.isShow = true;
        this.activeName = this.tabs[0].name;
        this.getData();
    }

    filterNode(value: any, data: any) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
    }

    close() {
        this.isShow = false;
        this.$emit("close");
    }

    confirm() {
        this.$emit("confirm", {
            list: this.itemList
        });
        this.isShow = false;
    }

    async getData() {
        const [res, reslut] = await Promise.all([
            this.$server["org/getMember"]({
                data: {
                    departmentId: "",
                    pageSize: 999,
                    currentPage: 1
                },
                loader: false
            }),
            this.$server["process/getGovernmentUser"]({
                data: {
                    governmentId: this.authArea.governmentId
                },
                loader: false
            })
        ]);
        if (res.data.code === 200) {
            const arrObj: any = {};
            res.data.data.records
                .filter((item: any) => item.id !== this.user.id)
                .forEach((item: any) => {
                    if (arrObj[item.departmentId]) {
                        arrObj[item.departmentId].push({
                            ...item,
                            governmentName: item.departmentName
                        });
                    } else {
                        arrObj[item.departmentId] = [
                            {
                                ...item,
                                governmentName: item.departmentName
                            }
                        ];
                    }
                });
            const list: any[] = Object.values(arrObj);
            if (this.disabledList.length) {
                this.townData = list.map((item: any) => {
                    return (item = item.map((subItem: any) => {
                        return {
                            ...subItem,
                            disabled: this.disabledList.includes(subItem.id)
                        };
                    }));
                });
            } else {
                this.townData = list;
            }
        }
        if (reslut.data.code === 200) {
            const list = reslut.data.data.filter(
                (item: any) => item.id !== this.user.id
            );
            if (this.disabledList.length) {
                this.villageData = list.map((item: any) => {
                    return (item = item.map((subItem: any) => {
                        return {
                            ...subItem,
                            disabled: this.disabledList.includes(subItem.id)
                        };
                    }));
                });
            } else {
                this.villageData = list;
            }
        }
    }

    // tab切换
    handleTabclick() {
        this.judgmentState();
        if (this.activeName === "town") {
            this.filterText = "";
            this.$nextTick(() => {
                this.handeleSetChecked("town");
            });
        } else {
            this.filterValue = "";
            this.$nextTick(() => {
                this.handeleSetChecked("village");
            });
        }
    }

    // 判断选择的状态
    judgmentState() {
        let temp: any = [];
        const idList: any[] = [];
        const itemIdList: any[] = [];
        if (this.activeName === "town") {
            if (this.filterOptionsList && this.itemList) {
                this.filterOptionsList.forEach((item: any) => {
                    item.children.forEach((sub: any) => {
                        idList.push(sub.id);
                    });
                });
                this.itemList.forEach((item: any) => {
                    itemIdList.push(item.id);
                });
                temp = itemIdList.filter((item: any) => idList.includes(item));
                if (!temp.length) {
                    // console.log('没选');
                    this.isIndeterminate = false;
                    this.checkAll = false;
                }
                if (temp.length < idList.length && temp.length) {
                    // console.log('半选');
                    this.isIndeterminate = true;
                    this.checkAll = true;
                }
                if (temp.length === idList.length) {
                    // console.log("全选");
                    this.isIndeterminate = false;
                    this.checkAll = true;
                }
            }
        }
        if (this.activeName === "village") {
            if (this.newVillageData && this.itemList.length) {
                this.newVillageData.forEach((item: any) => {
                    item.children.forEach((sub: any) => {
                        idList.push(sub.id);
                    });
                });
                this.itemList.forEach((item: any) => {
                    itemIdList.push(item.id);
                });
                temp = itemIdList.filter((item: any) => idList.includes(item));
                if (!temp.length) {
                    // console.log('没选');
                    this.isIndeterminate1 = false;
                    this.checkAll1 = false;
                }
                if (temp.length < idList.length && temp.length) {
                    // console.log('半选');
                    this.isIndeterminate1 = true;
                    this.checkAll1 = true;
                }
                if (temp.length === idList.length) {
                    // console.log("全选");
                    this.isIndeterminate1 = false;
                    this.checkAll1 = true;
                }
            }
        }
    }

    // 设置全选状态
    handeleSetChecked(tab: any) {
        const idList: any = [];
        this.itemList.forEach((item: any) => {
            idList.push(item.id);
        });
        this.$nextTick(() => {
            (this.$refs[tab] as any).setCheckedKeys(idList);
        });
    }

    handlecheck(data: any, node: any) {
        if (this.activeName === "town") {
            const idList: any[] = [];
            if (this.filterOptionsList) {
                this.filterOptionsList.forEach((item: any) => {
                    item.children.forEach((sub: any) => {
                        idList.push(sub.id);
                    });
                });
            }
            this.townitemList = node.checkedNodes.filter(
                (item: any) => !item.children
            );
            this.checkAll =
                this.townitemList.length === idList.length;
            this.isIndeterminate =
                this.townitemList.length > 0 &&
                this.townitemList.length < idList.length;
        }
        if (this.activeName === "village") {
            const idList: any[] = [];
            if (this.newVillageData) {
                this.newVillageData.forEach((item: any) => {
                    item.children.forEach((sub: any) => {
                        idList.push(sub.id);
                    });
                });
            }
            this.villageitemList = node.checkedNodes.filter(
                (item: any) => !item.children
            );
            this.checkAll1 =
                this.villageitemList.length === idList.length;
            this.isIndeterminate1 =
                this.villageitemList.length > 0 &&
                this.villageitemList.length < idList.length;
        }
        this.itemList = [
            ...this.townitemList,
            ...this.villageitemList
        ];
        const map = new Map();
        for (const item of this.itemList) {
            if (!map.has(item.id)) {
                map.set(item.id, item);
            }
        }

        this.itemList = [...map.values()];
    }

    deleteItem(i: any) {
        this.itemList.splice(i, 1);
        this.judgmentState();
        if (this.activeName === "town") {
            this.handeleSetChecked("town");
        } else {
            this.handeleSetChecked("village");
        }
    }

    // 顶部全选框操作时
    handleCheckAllChange(val: any) {
        this.isIndeterminate = false;
        if (val) {
            if (this.filterOptionsList) {
                this.filterOptionsList.forEach((item: any) => {
                    item.children.forEach((subItem: any) => {
                        this.townitemList.push(subItem);
                    });
                });
            }
        } else {
            const list: any = this.townitemList.filter(
                (item: any) => this.disabledList.includes(item.id)
            );
            this.townitemList = [].concat(list);
        }
        this.itemList = [
            ...this.townitemList,
            ...this.villageitemList
        ];
        const map = new Map();
        for (const item of this.itemList) {
            if (!map.has(item.id)) {
                map.set(item.id, item);
            }
        }
        this.itemList = [...map.values()];
        this.judgmentState();
        this.handeleSetChecked("town");
    }

    handleCheckAllChangevillage(val: any) {
        this.isIndeterminate1 = false;
        if (val) {
            if (this.newVillageData) {
                this.newVillageData.forEach((item: any) => {
                    item.children.forEach((subItem: any) => {
                        this.villageitemList.push(subItem);
                    });
                });
            }
        } else {
            const list: any = this.villageitemList.filter(
                (item: any) => this.disabledList.includes(item.id)
            );
            this.villageitemList = [].concat(list);
        }
        this.itemList = [
            ...this.townitemList,
            ...this.villageitemList
        ];
        const map = new Map();
        for (const item of this.itemList) {
            if (!map.has(item.id)) {
                map.set(item.id, item);
            }
        }
        this.itemList = [...map.values()];
        this.judgmentState();
        this.handeleSetChecked("village");
    }
}
</script>
